<template>
  <view class="webview-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @tap="goBack">
        <text class="nav-icon">←</text>
        <text class="nav-text">返回</text>
      </view>
      <view class="nav-title">{{ pageTitle }}</view>
      <view class="nav-right">
        <text class="nav-icon" @tap="refreshPage">🔄</text>
      </view>
    </view>
    
    <!-- WebView 容器 -->
    <view class="webview-wrapper">
      <web-view 
        ref="webviewRef"
        :src="htmlUrl" 
        @message="handleHtmlMessage"
        @error="handleWebViewError"
        @load="handleWebViewLoad"
      ></web-view>
    </view>
    
    <!-- 底部控制栏 -->
    <view class="control-bar">
      <button class="control-btn" @tap="sendMessageToHtml">
        📤 发送消息
      </button>
      <button class="control-btn" @tap="refreshPage">
        🔄 刷新
      </button>
      <button class="control-btn" @tap="showInfo">
        ℹ️ 信息
      </button>
    </view>
    
    <!-- 消息显示区域 -->
    <view v-if="showMessageArea" class="message-area">
      <view class="message-header">
        <text class="message-title">通信日志</text>
        <text class="message-close" @tap="toggleMessageArea">×</text>
      </view>
      <scroll-view class="message-content" scroll-y>
        <view 
          v-for="(msg, index) in messageLog" 
          :key="index" 
          class="message-item"
          :class="msg.type"
        >
          <text class="message-time">{{ msg.time }}</text>
          <text class="message-text">{{ msg.content }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { navigateTo } from '@/utils/navigation';

export default {
  data() {
    return {
      htmlUrl: '/static/html/index.html',
      pageTitle: 'HTML 页面',
      messageLog: [],
      showMessageArea: false,
      webviewLoaded: false
    };
  },
  
  onLoad(options) {
    console.log('WebView 页面加载，参数:', options);
    
    // 如果有传入的 URL 参数，使用传入的 URL
    if (options.url) {
      this.htmlUrl = decodeURIComponent(options.url);
      console.log('使用传入的 URL:', this.htmlUrl);
    }
    
    // 如果有传入的标题参数，使用传入的标题
    if (options.title) {
      this.pageTitle = decodeURIComponent(options.title);
    }
    
    this.addMessage('页面加载完成', 'info');
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 刷新页面
    refreshPage() {
      this.addMessage('刷新页面', 'info');
      // 重新加载 web-view
      this.$refs.webviewRef && this.$refs.webviewRef.evalJS('location.reload();');
    },
    
    // 处理 HTML 发送的消息
    handleHtmlMessage(e) {
      console.log('收到 HTML 消息:', e.detail.data);
      const message = e.detail.data;
      
      this.addMessage(`收到 HTML 消息: ${JSON.stringify(message)}`, 'from-html');
      
      // 根据消息类型处理不同的逻辑
      if (message.action === 'fromHtml') {
        this.handleHtmlAction(message);
      }
    },
    
    // 处理 HTML 动作
    handleHtmlAction(message) {
      switch (message.data?.type) {
        case 'greeting':
          uni.showToast({
            title: '收到 HTML 问候！',
            icon: 'success'
          });
          break;
        default:
          console.log('未处理的 HTML 动作:', message);
      }
    },
    
    // 向 HTML 发送消息
    sendMessageToHtml() {
      const message = {
        action: 'fromUniApp',
        content: 'Hello from UniApp!',
        timestamp: new Date().toISOString(),
        data: {
          type: 'greeting',
          value: '来自 uni-app 的问候'
        }
      };
      
      this.addMessage(`发送消息到 HTML: ${JSON.stringify(message)}`, 'to-html');
      
      // 调用 HTML 中的函数
      if (this.$refs.webviewRef) {
        this.$refs.webviewRef.evalJS(`receiveMessage(${JSON.stringify(message)});`);
      }
    },
    
    // 显示页面信息
    showInfo() {
      const info = {
        url: this.htmlUrl,
        title: this.pageTitle,
        loaded: this.webviewLoaded,
        messageCount: this.messageLog.length
      };
      
      uni.showModal({
        title: '页面信息',
        content: JSON.stringify(info, null, 2),
        showCancel: false
      });
    },
    
    // 切换消息区域显示
    toggleMessageArea() {
      this.showMessageArea = !this.showMessageArea;
    },
    
    // 添加消息到日志
    addMessage(content, type = 'info') {
      const message = {
        content,
        type,
        time: new Date().toLocaleTimeString('zh-CN')
      };
      
      this.messageLog.unshift(message);
      
      // 限制消息数量，避免内存占用过多
      if (this.messageLog.length > 50) {
        this.messageLog = this.messageLog.slice(0, 50);
      }
    },
    
    // 处理 WebView 加载完成
    handleWebViewLoad() {
      console.log('WebView 加载完成');
      this.webviewLoaded = true;
      this.addMessage('WebView 加载完成', 'info');
    },
    
    // 处理 WebView 错误
    handleWebViewError(e) {
      console.error('WebView 错误:', e);
      this.addMessage(`WebView 错误: ${JSON.stringify(e)}`, 'error');
      
      uni.showToast({
        title: '页面加载失败',
        icon: 'error'
      });
    }
  }
};
</script>

<style scoped>
.webview-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
  height: 44px;
}

.nav-left {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.nav-icon {
  font-size: 18px;
  margin-right: 5px;
}

.nav-text {
  font-size: 14px;
  color: #333;
}

.nav-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.nav-right {
  display: flex;
  align-items: center;
}

.webview-wrapper {
  flex: 1;
  position: relative;
}

.control-bar {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
}

.control-btn {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 12px;
  cursor: pointer;
}

.control-btn:active {
  transform: scale(0.95);
}

.message-area {
  position: absolute;
  bottom: 60px;
  left: 10px;
  right: 10px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 200px;
  z-index: 1000;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #e0e0e0;
}

.message-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.message-close {
  font-size: 18px;
  color: #999;
  cursor: pointer;
}

.message-content {
  max-height: 150px;
  padding: 10px;
}

.message-item {
  margin-bottom: 8px;
  padding: 8px;
  border-radius: 6px;
  font-size: 12px;
}

.message-item.info {
  background-color: #e3f2fd;
  color: #1976d2;
}

.message-item.from-html {
  background-color: #f3e5f5;
  color: #7b1fa2;
}

.message-item.to-html {
  background-color: #e8f5e8;
  color: #388e3c;
}

.message-item.error {
  background-color: #ffebee;
  color: #d32f2f;
}

.message-time {
  font-size: 10px;
  opacity: 0.7;
  margin-right: 5px;
}

.message-text {
  word-break: break-all;
}
</style> 